<?php
class Sms
{
	
	public $postdataArray;//提交的数组
	public $post_timeOut=30;
	public $public_Encryption_key='ZQ_sms_key';//加密偏移量
	public $post_url="";  // 远程访问地址,不过现在不起作用
	public $return_xml="";		//返回的xml
	private $setting=array();
	private $url = '';
	private $status = array(
		"00"  => "批量短信提交成功（批量短信待审批）",
		"01"  => "批量短信提交成功（批量短信跳过审批环节）",
		"02"  => "服务器IP受限制",
		"03"  => "单条短信提交成功",
		"04"  => "用户名错误",
		"05" => "密码错误",
		"06" => "剩余条数不足",
		"07" => "信息内容中含有限制词(违禁词)",
		"08" => "信息内容为黑内容",
		"09" => "该用户的该内容 受同天内内容不能重复发 限制",
		"10" => "批量下限不足",
		"97" => "短信参数有误",
		"98" => "防火墙无法处理这种短信"
	);
	
	public function __construct()
    {

		/*$smsInfo =array(
			'OperID'=>'zqkjtg',
			'OperPass'=>'fpt5d3mt',
			//'server_url'=>'http://221.179.180.158:9000/QxtSms/QxtFirewall',
			'SendTime'=>'',
			'ValidTime'=>'',
			'AppendID'=>'',
			'ContentType'=>'15'
			
			
		);*/


		$this->setting=array(
			'enterpriseID'=>'13080',
			'loginName'=>'admin',
			'password'=>md5('mytf//k1241'),
			'smsId'=>'',
			'subPort'=>''
		);
		$this->url = 'http://119.145.9.12/sendSMS.action';

	}
	
	function sendSMS($mobiles,$message,$sendTime=''){
		if($mobiles){
			if(is_array($mobiles)){
				$mobiles = implode(",",$mobiles);
			}		
			$setting = $this->setting;
			$setting['sendTime']=$sendTime;
			$setting['mobiles']=$mobiles;
			//$setting['content']=mb_convert_encoding($message,"UTF-8","auto");
			$setting['content']=$message;
			//$setting['content']='短的好像很快,这是简体,這是繁體,time:'.date("Y-m-d H:i:s");
			$result = $this->post_data($this->url,$setting);
			return $result;
			//dump($setting['Content']);
			//dump($status);
			//dump($this->get_xml());				
		}else{
			return 0;	
			
		}
		
	}


	function postdata($data=array())
	{
		if(count($data)>0)
		$this->postdataArray=$data;
	}

	/**
	 * 提交发送数据返回已序列化的PHP数据内容
	 *
	 * @param string $PostUrl 要指交的远程地址
	 * @param array $data 要提交的数据
     * @return obj  远程返回的对像
	 */
	function getWebServerData($PostUrl,$data)
	{
		$postReturnData=$this->post_data($PostUrl,$data);
		return unserialize($postReturnData);
	}

	/**
	 * 提交发送数据返回已序化的加密数据内容,回来还要解密
	 *
	 * @param unknown_type $PostUrl
	 * @param unknown_type $data
	 * @return unknown
	 */
	function getCrtyWebServerData($PostUrl,$data=array())
	{
		$postReturnData=$this->post_data($PostUrl,$data);
		if($postReturnData=="false") return "false";
		//return $postReturnData;
		//return $this->StrCode($postReturnData,$this->public_Encryption_key,'DECODE');
		return unserialize($this->StrCode($postReturnData,$this->public_Encryption_key,'DECODE'));
	}

	/**
	 * 字符串加解密
	 *
	 * $str=$Function_Class->strCode("abc","哈哈","ENCODE");
	 *$str=$Function_Class->strCode($str,"哈哈","DECODE");
	 * 
	 * 
	 * @param string $string  要处理的字符串
	 * @param string $offKey  加密的偏移量    为空则为拿当前用户请求的IP
	 * @param string $action  ENCODE加密    DECODE解密
	 * @return string
	 */
	function StrCode($string,$offKey="",$action='ENCODE'){
		if($offKey=="")
		$key	= substr(md5($_SERVER["HTTP_USER_AGENT"]),8,18);
		else
		$key=substr(md5($offKey),8,18);
		unset($offKey);
		$string	= $action == 'ENCODE' ? $string : base64_decode($string);
		$len	= strlen($key);
		$code	= '';
		for($i=0; $i<strlen($string); $i++){
			$k		= $i % $len;
			$code  .= $string[$i] ^ $key[$k];
		}
		$code = $action == 'DECODE' ? $code : base64_encode($code);
		return $code;
	}



	
	/**
     * 表单模拟提交发送
     *
     * @param string $PostUrl  要指交的远程地址
     * @param array $data    要提交的数据
     * @return string 
     */
	function post_data($PostUrl,$data=array())
	{
		if(!strstr($PostUrl,"http://")){
			echo $PostUrl  = 'http://'.$PostUrl;
		}
		
		if(count($data)>0)
		$this->postdataArray=$data;
		//检测输入
		$url_file = trim($PostUrl);
		if (empty($url_file)) { return false; }
		$url_arr = parse_url($url_file);
		
		if (!is_array($url_arr) || empty($url_arr)){ return false; }
		//获取请求数据
		$host = $url_arr['host'];
		if(!empty($url_arr['query'])&&$url_arr['query']!=null)
			$path = $url_arr['path'] ."?". $url_arr['query'];
		else 
			$path = $url_arr['path'];
		$port = isset($url_arr['port']) ? $url_arr['port'] : "80";
	
		//连接服务器
		$fp = fsockopen($host, $port, $err_no, $err_str, $this->post_timeOut);
		if (!$fp){ return false; }
		$ret="";
		$out = "";
		while (list ($k, $v) = each ($this->postdataArray)) {
			if(strlen($out) != 0) $out .= "&";
			$out .= rawurlencode($k). "=" .rawurlencode($v);
		}
		
		$out = trim ($out);
		$request     =   "POST ".$path."  HTTP/1.0\r\n";
		$request   .=   "Host: ".$host."\r\n";
		$request   .=   "User-Agent: Incutio HttpClient v0.9\r\n";
		$request   .=    "Accept: text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*\r\n";
		$request   .=   "Accept-encoding: gzip\r\n";
		$request   .=   "Accept-Language:   zh-cn\r\n";
		$request   .=   "Content-Type:   application/x-www-form-urlencoded\r\n";
		$request   .=   "Content-length:   ".strlen($out)."\r\n";
		//$request   .=   "Connection:   Keep-Alive\r\n\r\n";			//响应很慢
		$request   .=   "Connection:  close\r\n\r\n";
		$request.=$out;
		
		fputs($fp,$request);
		unset($request);
		$inHeaders = true;
		$atStart = true;
		while(!feof($fp)){
			$line = fgets($fp, 4096);
			
			if ($atStart) {
				// 是否第一次返回数据
				$atStart = false;
				if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
					return false;
				}
				continue;
			}
			if ($inHeaders) {
				if (trim($line) == '') {
					$inHeaders = false;
					continue;
				}
				if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
					continue;
				}
				continue;
			}
			$ret.= $line;
		}
		fclose ($fp);
		
		//return $ret;
		$this->return_xml = $ret;
		if (preg_match ("/\<Result\>([\-0-9]{1,2})\<\/Result\>/", $ret,$array)) {			
			if($array[1]=='0'){														//返回的xml值 为0,即发送成功
				return true;   
		   }else{
			   	return false;  
		   }
		} else {
			return false;
		}
	}
	
	function get_xml(){		
		return $this->return_xml;
	}
	
	
	/**
	 * 设置提交数据
	 *
	 * @param obj $key
	 * @param obj $value
	 */
	function setPostData($key,$value)
	{
		$this->postdataArray[$key]=$value;
	}

	/**
	 * 函数：remote_file_exists
	*  功能：判断远程文件是否存在
	 *
	 * @param  string  $remoteFile  远程文件URL
	 * @return  bool 存在返回true，不存在或者其他原因返回false
	 */
	function remote_file_exists($remoteFile){
		//检测输入
		$url_file = trim($remoteFile);
		if (empty($url_file)) { return false; }
		$url_arr = parse_url($url_file);
		if (!is_array($url_arr) || empty($url_arr)){ return false; }

		//获取请求数据
		$host = $url_arr['host'];
		if(!empty($url_arr['query'])&&$url_arr['query']!=null)
			$path = $url_arr['path'] ."?". $url_arr['query'];
		else 
			$path = $url_arr['path'] ;
		$port = isset($url_arr['port']) ? $url_arr['port'] : "80";

		//连接服务器
		$fp = fsockopen($host, $port, $err_no, $err_str, 30);
		if (!$fp){ return false; }
		//构造请求协议
		$request_str = "GET ".$path." HTTP/1.1\r\n";
		$request_str .= "Host: ".$host."\r\n";
		$request_str .= "Connection: Close\r\n\r\n";
		//发送请求
		fwrite($fp, $request_str);
		$first_header = fgets($fp, 1024);
		fclose($fp);
		//判断文件是否存在
		if (trim($first_header) == ""){ return false; }
		if (!preg_match("/200/", $first_header)){
			return false;
		}
		return true;
	}
}


//$send_phone_str = '13928491884';				//多个时为数组
//$message = '请您加入【G媒】啦！参与G层关注，分享收益！下载：http://m.shoumedia.com()'.date("Y-m-d");
//$sms=new Sms();
//$rs = $sms->sendSMS($send_phone_str,$message);




?>